package cluster

import (
	"fmt"
	"log"
	"strings"
)

// CleanupEnvironment 清理集群环境
func (m *Manager) CleanupEnvironment() {
	// 停止和禁用 containerd 服务
	_ = m.executor.RunCommand("systemctl", "stop", "containerd")
	_ = m.executor.RunCommand("systemctl", "disable", "containerd")

	// 清理 containerd 相关文件和目录
	cleanupCommands := []string{
		"sudo rm -f /usr/local/bin/containerd /usr/bin/containerd",
		"sudo rm -f /usr/local/bin/containerd-shim /usr/bin/containerd-shim",
		"sudo rm -f /usr/local/bin/containerd-shim-runc-v1 /usr/bin/containerd-shim-runc-v1",
		"sudo rm -f /usr/local/bin/containerd-shim-runc-v2 /usr/bin/containerd-shim-runc-v2",
		"sudo rm -f /usr/local/bin/ctr /usr/bin/ctr",
		"sudo rm -rf /etc/containerd",
		"sudo rm -rf /var/lib/containerd",
		"sudo rm -rf /var/run/containerd",
		"sudo rm -rf /run/containerd",
	}

	// 添加配置文件中定义的存储路径清理命令
	cleanupCommands = append(cleanupCommands,
		fmt.Sprintf("sudo rm -rf %s", m.env["SEALOS_RUNTIME_ROOT"]),
		fmt.Sprintf("sudo rm -rf %s", m.env["SEALOS_DATA_ROOT"]),
		fmt.Sprintf("sudo rm -rf %s", m.env["CONTAINER_RUNROOT"]),
		fmt.Sprintf("sudo rm -rf %s", m.env["CONTAINER_GRAPHROOT"]),
		fmt.Sprintf("sudo rm -f %s", m.env["CONTAINERS_STORAGE_CONF"]),
	)

	// 执行清理命令
	for _, cmd := range cleanupCommands {
		_ = m.executor.RunCommand("bash", "-c", cmd)
	}

	// 卸载 containerd 包
	_ = m.executor.RunCommand("apt-get", "remove", "-y", "containerd.io")
	_ = m.executor.RunCommand("apt-get", "purge", "-y", "containerd.io")

	// 使用配置文件中的值重置集群
	masters := strings.Join(m.cfg.Cluster.Masters, ",")
	nodes := strings.Join(m.cfg.Cluster.Nodes, ",")

	// 构建 reset 命令
	resetCmd := fmt.Sprintf("echo 'master01' | sealos reset --masters %s --nodes %s --force", masters, nodes)
	if err := m.executor.RunCommand("bash", "-c", resetCmd); err != nil {
		log.Printf("重置集群警告: %v", err)
	}

	// 清理系统残留
	_ = m.executor.RunCommand("apt-get", "autoremove", "-y")
	_ = m.executor.RunCommand("apt-get", "clean")

	log.Println("环境清理完成")
}
